package com.qf.blog.interceptor;

import com.qf.blog.auth.LoginThreadLocal;
import com.qf.blog.constatns.LoginConstatns;
import com.qf.blog.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginUserInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前登录用户
        User user = (User) request.getSession().getAttribute(LoginConstatns.LOGIN_USER_KEY);
        LoginThreadLocal.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //后台controller执行后从ThreadLocal中删除信息
        //不删除可能会出现线程不安全问题
        User user = LoginThreadLocal.get();
        if (user != null) {
        LoginThreadLocal.remove();
        }


        Object loginUser = request.getSession().getAttribute(LoginConstatns.LOGIN_USER_KEY);

        if(loginUser != null && modelAndView != null){
        modelAndView.addObject(LoginConstatns.LOGIN_USER_KEY,loginUser);
        }
    }
}
